<template>
  <div class="flex flex-col min-h-screen bg-slate-50">
    <!-- 编辑器头部 -->
    <div class="flex justify-between items-center px-8 py-4 border-b border-slate-200 bg-white sticky top-0 z-10 shadow-sm">
      <div class="flex items-center gap-6">
        <button 
          @click="goBack" 
          class="flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium text-slate-500 bg-slate-50 border border-slate-200 hover:bg-slate-100 hover:text-slate-600 transition-colors"
        >
          <ChevronLeftIcon class="w-5 h-5" />
          <span>返回</span>
        </button>
        <h1 class="text-xl font-semibold text-slate-700">{{ isEditMode ? '编辑文章' : '创建新文章' }}</h1>
      </div>
      
      <div class="flex items-center gap-2 text-sm text-slate-400">
        <span>{{ saveStatusText }}</span>
      </div>
    </div>
    
    <!-- 编辑器内容 -->
    <div class="flex-1 px-8 py-8 overflow-y-auto max-w-3xl mx-auto w-full">
      <!-- 步骤导航 -->
      <div class="mb-8">
        <div class="flex items-center">
          <div 
            v-for="(step, index) in steps" 
            :key="step.name"
            class="flex items-center"
          >
            <div 
              class="flex items-center justify-center w-8 h-8 rounded-full text-sm font-medium transition-colors"
              :class="[
                currentStep === step.name ? 'bg-slate-600 text-white' : 
                completedSteps.includes(step.name) ? 'bg-slate-100 text-slate-600' : 'bg-slate-100 text-slate-400'
              ]"
            >
              {{ index + 1 }}
            </div>
            <div 
              v-if="index < steps.length - 1" 
              class="w-16 h-0.5 mx-1"
              :class="[
                completedSteps.includes(step.name) ? 'bg-slate-300' : 'bg-slate-200'
              ]"
            ></div>
          </div>
        </div>
      </div>
      
      <!-- 步骤内容 -->
      <component 
        :is="currentStepComponent"
        @next="handleNextStep"
        @prev="handlePrevStep"
        @publish="handlePublish"
        :base-url="baseUrl"
        :categories="categories"
        :tags="tags"
      ></component>
    </div>

    <!-- 离开确认对话框 -->
    <confirm-dialog
      :show="showLeaveConfirm"
      @confirm="confirmLeave"
      @cancel="cancelLeave"
      @close="cancelLeave"
      title="确认离开"
      content="您有未保存的更改，确定要离开吗？"
      :confirmText="'确定离开'"
      :cancelText="'取消'"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue';
import { useArticleEditorStore } from '@/stores/articleEditor';
import { useToast } from '@/Composables/useToast';
import { useArticleSubmit } from '@/Composables/useArticleSubmit';
import { useEditorShortcuts } from '@/Composables/useEditorShortcuts';
import { router } from '@inertiajs/vue3';
import StepNavigation from './Components/StepNavigation.vue';
import ContentStep from './Steps/ContentStep.vue';
import CategoryTagStep from './Steps/CategoryTagStep.vue';
import PublishStep from './Steps/PublishStep.vue';
import ConfirmDialog from '@/Components/UI/ConfirmDialog.vue';
import { ChevronLeftIcon } from '@heroicons/vue/20/solid';

const props = defineProps({
  post: {
    type: Object,
    default: null
  },
  categories: {
    type: Array,
    required: true,
    default: () => []
  },
  tags: {
    type: Array,
    required: true,
    default: () => []
  },
  user: {
    type: Object,
    required: true
  },
  baseUrl: {
    type: String,
    default: '/'
  }
});

const emit = defineEmits(['close']);
const editorStore = useArticleEditorStore();
const toast = useToast();
const { submitArticle } = useArticleSubmit();
const showLeaveConfirm = ref(false);

// 本地存储键名
const getStorageKey = () => {
  const userId = props.user?.id || 'guest';
  const postId = props.post?.id || 'new';
  return `draft_${userId}_${postId}`;
};

// 步骤定义
const steps = [
  { name: 'content', label: '内容' },
  { name: 'category-tag', label: '分类和标签' },
  { name: 'publish', label: '发布' }
];

// 当前步骤
const currentStep = ref('content');

// 已完成的步骤
const completedSteps = ref([]);

// 计算当前步骤对应的组件
const currentStepComponent = computed(() => {
  switch(currentStep.value) {
    case 'content': return ContentStep;
    case 'category-tag': return CategoryTagStep;
    case 'publish': return PublishStep;
    default: return ContentStep;
  }
});

// 计算属性
const isEditMode = computed(() => !!props.post);
const saveStatusText = computed(() => {
  if (editorStore.hasUnsavedChanges) return '未保存';
  if (editorStore.lastSavedTime) {
    const date = new Date(editorStore.lastSavedTime);
    return `已保存 ${date.toLocaleTimeString()}`;
  }
  return '已保存';
});

const canProceedToNextStep = computed(() => {
  switch (currentStep.value) {
    case 'content':
      return !!editorStore.title.trim() && !!editorStore.content.trim();
    case 'category-tag':
      return !!editorStore.categoryId;
    case 'publish':
      return true;
    default:
      return false;
  }
});

// 方法
const goBack = () => {
  if (editorStore.hasUnsavedChanges) {
    showLeaveConfirm.value = true;
  } else {
    router.visit(route('author.posts.index'));
  }
};

const confirmLeave = () => {
  showLeaveConfirm.value = false;
  router.visit(route('author.posts.index'));
};

const cancelLeave = () => {
  showLeaveConfirm.value = false;
};

// 保存草稿到本地存储
const saveDraftToLocal = () => {
  try {
    const draftData = {
      title: editorStore.title,
      content: editorStore.content,
      excerpt: editorStore.excerpt,
      slug: editorStore.slug,
      categoryId: editorStore.categoryId,
      tags: editorStore.tags,
      status: editorStore.status,
      scheduledTime: editorStore.scheduledTime,
      featuredImage: editorStore.featuredImage,
      settings: editorStore.settings,
      updated_at: new Date().toISOString()
    };
    
    localStorage.setItem(getStorageKey(), JSON.stringify(draftData));
    editorStore.markAsSaved();
  } catch (error) {
    if (process.env.NODE_ENV === 'development') {
      console.error('保存草稿失败:', error);
    }
  }
};

// 从本地存储加载草稿
const loadDraftFromLocal = () => {
  try {
    const savedData = localStorage.getItem(getStorageKey());
    if (savedData && !isEditMode.value) {
      const draftData = JSON.parse(savedData);
      editorStore.title = draftData.title || '';
      editorStore.content = draftData.content || '';
      editorStore.excerpt = draftData.excerpt || '';
      editorStore.slug = draftData.slug || '';
      editorStore.categoryId = draftData.categoryId || null;
      editorStore.tags = draftData.tags || [];
      editorStore.status = draftData.status || 'draft';
      editorStore.scheduledTime = draftData.scheduledTime || null;
      editorStore.featuredImage = draftData.featuredImage || null;
      if (draftData.settings) {
        editorStore.settings = { ...editorStore.settings, ...draftData.settings };
      }
      editorStore.markAsSaved();
    }
  } catch (error) {
    if (process.env.NODE_ENV === 'development') {
      console.error('加载草稿失败:', error);
    }
  }
};

// 清除本地草稿
const clearLocalDraft = () => {
  try {
    localStorage.removeItem(getStorageKey());
  } catch (error) {
    if (process.env.NODE_ENV === 'development') {
      console.error('清除草稿失败:', error);
    }
  }
};

const handleNextStep = () => {
  if (!canProceedToNextStep.value) {
    toast('请完成当前步骤的所有必填项', 'error');
    return;
  }
  
  // 记录当前步骤为已完成
  if (!completedSteps.value.includes(currentStep.value)) {
    completedSteps.value.push(currentStep.value);
  }
  
  // 前进到下一个步骤
  const currentIndex = steps.findIndex(step => step.name === currentStep.value);
  if (currentIndex < steps.length - 1) {
    currentStep.value = steps[currentIndex + 1].name;
  }
  
  // 自动保存当前进度（静默保存）
  if (!isEditMode.value) {
    saveDraftToLocal();
  }
};

const handlePrevStep = () => {
  // 后退到上一个步骤
  const currentIndex = steps.findIndex(step => step.name === currentStep.value);
  if (currentIndex > 0) {
    currentStep.value = steps[currentIndex - 1].name;
  }
};

const handlePublish = async (publishData) => {
  try {
    // 使用 composable 提交文章
    await submitArticle(
      publishData,
      isEditMode.value,
      props.post?.slug || null,
      () => clearLocalDraft(), // 发布成功后清除本地草稿
      editorStore
    );
    
    // 提交成功后，Inertia 会自动处理后端的重定向
  } catch (error) {
    // 错误已在 composable 中处理
    if (process.env.NODE_ENV === 'development') {
      console.error('发布失败', error);
    }
  }
};

// 处理发布（从快捷键触发）
const handlePublishFromShortcut = () => {
  // 如果当前在发布步骤，触发发布
  if (currentStep.value === 'publish') {
    // 获取发布数据
    const publishData = {
      title: editorStore.title,
      content: editorStore.content,
      excerpt: editorStore.excerpt,
      slug: editorStore.slug,
      categoryId: editorStore.categoryId,
      tags: editorStore.tags,
      status: editorStore.status,
      scheduled_at: editorStore.scheduledTime,
      featuredImage: editorStore.featuredImage,
      featuredImageUrl: editorStore.featuredImageUrl,
      settings: editorStore.settings,
      seriesId: editorStore.seriesId,
      seriesOrder: editorStore.seriesOrder,
      sortMode: editorStore.sortMode
    };
    handlePublish(publishData);
  } else {
    toast('请先完成发布设置步骤', 'info');
  }
};

// 初始化键盘快捷键
useEditorShortcuts({
  onSave: () => {}, // 移除手动保存快捷键
  onPublish: handlePublishFromShortcut,
  onBack: goBack
});

// 自动保存（使用防抖优化性能）
let autoSaveTimer = null;
const AUTO_SAVE_INTERVAL = 3000; // 3秒防抖

watch(() => editorStore.hasUnsavedChanges, (hasChanges) => {
  if (hasChanges && !isEditMode.value) {
    // 清除之前的定时器
    if (autoSaveTimer) {
      clearTimeout(autoSaveTimer);
    }
    
    // 防抖：3秒后自动保存
    autoSaveTimer = setTimeout(() => {
      saveDraftToLocal();
    }, AUTO_SAVE_INTERVAL);
  }
});

// 生命周期钩子
onMounted(() => {
  // 如果有post数据，加载它（编辑模式）
  if (props.post) {
    // 将post数据加载到编辑器存储中
    editorStore.title = props.post.title || '';
    editorStore.content = props.post.content || '';
    editorStore.excerpt = props.post.excerpt || '';
    editorStore.slug = props.post.slug || '';
    editorStore.categoryId = props.post.category_id || null;
    editorStore.tags = props.post.tags || [];
    editorStore.status = props.post.status || 'draft';
    editorStore.scheduledTime = props.post.scheduled_publish_at || null;
    editorStore.featuredImage = props.post.featured_image || null;
    
    if (props.post.settings) {
      editorStore.settings = {
        ...editorStore.settings,
        ...props.post.settings
      };
    }
    
    // 初始化完成后标记为已保存状态
    editorStore.markAsSaved();
  } else {
    // 如果没有post数据，先尝试从本地存储恢复草稿（静默恢复）
    loadDraftFromLocal();
    
    // 如果没有草稿，重置编辑器状态
    if (!editorStore.title && !editorStore.content) {
      editorStore.$reset();
    }
  }
  
  // 初始标记第一个步骤为当前步骤
  currentStep.value = 'content';
  
  // 页面关闭前保存
  window.addEventListener('beforeunload', () => {
    if (editorStore.hasUnsavedChanges && !isEditMode.value) {
      saveDraftToLocal();
    }
  });
});

onBeforeUnmount(() => {
  // 清理定时器
  if (autoSaveTimer) {
    clearTimeout(autoSaveTimer);
  }
  
  // 最后保存一次
  if (editorStore.hasUnsavedChanges && !isEditMode.value) {
    saveDraftToLocal();
  }
});
</script>

<style scoped>
.article-editor {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8fafc;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 2rem;
  border-bottom: 1px solid #e2e8f0;
  background-color: #ffffff;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 1.5rem;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  font-weight: 500;
  color: #64748b;
  background-color: #f8fafc;
  border: 1px solid #e2e8f0;
  cursor: pointer;
  transition: all 0.2s ease;
}

.back-button:hover {
  background-color: #f1f5f9;
  color: #475569;
}

.back-button svg {
  width: 1.25rem;
  height: 1.25rem;
}

.editor-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #334155;
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.save-status {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.875rem;
  color: #94a3b8;
}

.save-status svg {
  width: 1rem;
  height: 1rem;
}

.save-status .spin {
  animation: spin 1s linear infinite;
}

.save-button {
  padding: 0.5rem 1rem;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  font-weight: 500;
  background-color: #f8fafc;
  border: 1px solid #e2e8f0;
  color: #64748b;
  cursor: pointer;
  transition: all 0.2s ease;
}

.save-button:hover:not(:disabled) {
  background-color: #f1f5f9;
  color: #475569;
}

.save-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.draft-recovery-alert {
  margin: 1rem 2rem;
  padding: 1rem;
  background-color: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 0.5rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.alert-content {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.alert-content svg {
  color: #64748b;
}

.alert-actions {
  display: flex;
  gap: 0.75rem;
}

.btn-secondary, .btn-primary {
  padding: 0.5rem 1rem;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn-secondary {
  background-color: #f8fafc;
  border: 1px solid #e2e8f0;
  color: #64748b;
}

.btn-secondary:hover {
  background-color: #f1f5f9;
  color: #475569;
}

.btn-primary {
  background-color: #4b5563;
  border: 1px solid transparent;
  color: #ffffff;
}

.btn-primary:hover {
  background-color: #374151;
}

.editor-content {
  flex: 1;
  padding: 2rem;
  overflow-y: auto;
  max-width: 900px;
  margin: 0 auto;
  width: 100%;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 深色模式 */
:deep(.dark-mode) .article-editor {
  background-color: #0f172a;
}

:deep(.dark-mode) .editor-header {
  background-color: #1e293b;
  border-bottom-color: #334155;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

:deep(.dark-mode) .back-button,
:deep(.dark-mode) .save-button {
  background-color: #1e293b;
  border-color: #334155;
  color: #94a3b8;
}

:deep(.dark-mode) .back-button:hover,
:deep(.dark-mode) .save-button:hover:not(:disabled) {
  background-color: #334155;
  color: #e2e8f0;
}

:deep(.dark-mode) .editor-title {
  color: #f1f5f9;
}

:deep(.dark-mode) .save-status {
  color: #94a3b8;
}

:deep(.dark-mode) .draft-recovery-alert {
  background-color: #1e293b;
  border-color: #334155;
  color: #f1f5f9;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

:deep(.dark-mode) .alert-content svg {
  color: #94a3b8;
}

:deep(.dark-mode) .btn-secondary {
  background-color: #1e293b;
  border-color: #334155;
  color: #94a3b8;
}

:deep(.dark-mode) .btn-secondary:hover {
  background-color: #334155;
  color: #e2e8f0;
}

:deep(.dark-mode) .btn-primary {
  background-color: #475569;
  color: #f8fafc;
}

:deep(.dark-mode) .btn-primary:hover {
  background-color: #64748b;
}

/* 移动适配 */
@media (max-width: 640px) {
  .editor-header {
    padding: 1rem;
  }
  
  .header-left {
    gap: 1rem;
  }
  
  .back-button {
    padding: 0.5rem;
  }
  
  .back-button span {
    display: none;
  }
  
  .editor-title {
    font-size: 1.125rem;
  }
  
  .editor-content {
    padding: 1rem;
  }
  
  .draft-recovery-alert {
    margin: 0.75rem;
    padding: 0.75rem;
    flex-direction: column;
    gap: 0.75rem;
  }
  
  .alert-content, .alert-actions {
    width: 100%;
  }
  
  .alert-actions {
    justify-content: flex-end;
  }
}
</style> 